package com.coman404.mvc.conf;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author NotFound404 at 2024/6/11
 * code code always code
 */

@Component
public class RequestDispatch {

    public Set<ControllerMappingHolder> holders = new HashSet<>(16);

    public void addHolder(ControllerMappingHolder holder){
        holders.add(holder);
    }

    public FullHttpResponse dispatch(FullHttpRequest request, FullHttpResponse response) {
        String uri = request.uri();
        HttpMethod method = request.method();
        QueryStringDecoder decoder = new QueryStringDecoder(uri);
        String path = decoder.path();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (ControllerMappingHolder holder : holders) {
            if (antPathMatcher.match(holder.getPath(), path) && holder.getMethodType().equalsIgnoreCase(method.name())) {
                try {
                    return holder.getHandler().handle(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                    response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    String msg = Optional.ofNullable(e.getMessage()).orElse(e.getClass().getName());
                    return response.replace(Unpooled.copiedBuffer(msg.getBytes(StandardCharsets.UTF_8)));
                }
            }
        }
        return response.setStatus(HttpResponseStatus.NOT_FOUND);
    }



}
